package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"test/common"
	"test/model"
)

func Find_allteacher(ctx *gin.Context) {
	var teachers []model.Teachers
	db := common.GetDB()
	result := db.Find(&teachers)
	fmt.Println(teachers)
	if result != nil {
		fmt.Println("data")
	}
	ctx.JSON(http.StatusOK,teachers)
}

func AddTeacher(ctx *gin.Context) {
	DB := common.GetDB()
	requestteacher := make(map[string]interface{})
	//获取参数
	var teachers model.Teachers
	DB.Last(&teachers)
	fmt.Println(teachers.Tno)
	ctx.ShouldBind(&requestteacher)
	fmt.Println(requestteacher,"我是添加教师")
	tno := teachers.Tno + 1
	tname := requestteacher["Tname"].(string)
	fmt.Println("1")
	trank := requestteacher["Trank"].(string)
	fmt.Println("2")
	tspeciality := requestteacher["Tspecialty"].(string)

	/*判断教师是否已经存在*/
	if isCnameExists(DB,tname) {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"教师已经存在"})
		fmt.Println("我执行了")
		return
	}
	newTeacher := model.Teachers {
		Tno: tno,
		Tname: tname,
		Trank: trank,
		Tspeciality: tspeciality,
	}
	DB.Create(&newTeacher)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "添加成功",
	})
}

func DeleteTeacher(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我执行了")
	requestteacher := make(map[string]interface{})
	var teachers model.Teachers
	//获取参数
	ctx.ShouldBind(&requestteacher)
	fmt.Println(requestteacher["Tno"].(float64),"教师号")
	teachers.Tno = int(requestteacher["Tno"].(float64))
	DB.Where("Tno = ?",teachers.Tno).Delete(&teachers)
}

func UpdateTeacher(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我是修该教师信息")
	requestteacher := make(map[string]interface{})
	//获取参数
	var teachers model.Teachers
	DB.Last(&teachers)
	ctx.ShouldBind(&requestteacher)
	teachers.Tno = int(requestteacher["Sno"].(float64))
	teachers.Tname=requestteacher["Tname"].(string)
	teachers.Trank = requestteacher["Trank"].(string)
	teachers.Tspeciality =requestteacher["Tspeciality"].(string)
	fmt.Println(teachers)
	DB.Where("sno = ?",teachers.Tno).Updates(&teachers)
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "修改成功",
	})
}

func FindTeacherByTno(ctx *gin.Context) {
	DB := common.GetDB()
	requeststudent := make(map[string]interface{})
	fmt.Println("修该执行")
	var teachers model.Teachers
	DB.Last(&teachers)
	ctx.ShouldBind(&requeststudent)
	ctx.JSON(http.StatusOK,requeststudent)
}
